package com.stock.stockana.ui.fragments;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.stock.stockana.R;
import com.stock.stockana.StockCenter;
import com.stock.stockana.beans.PushRecord;
import com.stock.stockana.beans.ResponseBean;
import com.stock.stockana.beans.StockInfoBean;
import com.stock.stockana.constants.NetWorkConstants;
import com.stock.stockana.events.network.DeletePushRecordEvent;
import com.stock.stockana.events.network.GetOneStockEvent;
import com.stock.stockana.events.network.GetPushRecordEvent;
import com.stock.stockana.requests.DeletePushRecord;
import com.stock.stockana.requests.GetOneStock;
import com.stock.stockana.requests.GetPushRecord;
import com.stock.stockana.ui.activities.MainActivity;
import com.stock.stockana.ui.activities.StockDetailActivity;

import java.text.SimpleDateFormat;
import java.util.Locale;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;

/**
 * Created by ljgsonx on 2016/3/6.
 */
public class PushRecordsFragment extends Fragment {

    private final static String TAG = "PushRecordsFragment--->";
    private ListView mPushRecordsLv;
    private PushRecordsLvAdapter mRecordsAdapter;
    private LinearLayout noItemTipLL;
    private LinearLayout mHeaderLL;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.pushrecord_layout, container, false);
        mPushRecordsLv = (ListView) view.findViewById(R.id.pushRecordsLv);
        noItemTipLL = (LinearLayout) view.findViewById(R.id.noItemTipLL);
//        initHeaderView();
//        mPushRecordsLv.addHeaderView(mHeaderLL);
        mRecordsAdapter = new PushRecordsLvAdapter();
        mPushRecordsLv.setAdapter(mRecordsAdapter);
        GetPushRecord getPushRecord = GetPushRecord.build();
        StockCenter.doReq(getPushRecord);
        return view;
    }

    private void initHeaderView(){
        mHeaderLL = (LinearLayout) LayoutInflater.from(getActivity()).inflate(R.layout.push_record_header_layout, null);
        TextView tv = (TextView) mHeaderLL.findViewById(R.id.clearAllTv);
        tv.setClickable(true);
        tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Dialog dialog = new AlertDialog.Builder(getActivity())
                        .setTitle("清空叫醒记录")
                        .setMessage("确认全部删除吗？")
                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                DeletePushRecord deletePushRecord = DeletePushRecord.build()
                                        .setDeleteFlag(DeletePushRecord.DELETE_ALL_FLAG);
                                StockCenter.doReq(deletePushRecord);
                                ((MainActivity) getActivity()).showProgress("正在清空...");
                            }
                        })
                        .setNegativeButton("取消", null).create();
                dialog.show();
            }
        });
    }

    @Subscribe
    public void onEventMainThread(GetPushRecordEvent event) {
        if (event.getResponseCode() == NetWorkConstants.RESPONSE_CODE_OK) {
            SharedPreferences sharedPreference = getActivity().getSharedPreferences("property", Context.MODE_PRIVATE);
            long lastPushRecordDate = sharedPreference.getLong("lastPushRecordDate", 0);
            long newRecordDate = 0;
            if(GetPushRecord.pushRecords.size() != 0){
                newRecordDate = GetPushRecord.pushRecords.get(0).getWakedDate().getTime();
            }
            if(lastPushRecordDate < newRecordDate) {
                TabLayout tabLayout = ((MainActivity) getActivity()).getTabLayout();
                TabLayout.Tab tab = tabLayout.getTabAt(3);
                if (tab != null) {
                    View view = tab.getCustomView();
                    if (view != null) {
                        ImageView iv = (ImageView) view.findViewById(R.id.pushRecordRedPointIv);
                        iv.setVisibility(View.VISIBLE);
                    }
                }
            }
            mRecordsAdapter.notifyDataSetChanged();
        }else{
            Log.d(TAG, event.getMessage());
            Toast.makeText(getActivity(), NetWorkConstants.RESPONSE_COMMON_MESSAGE, Toast.LENGTH_LONG).show();

        }
    }

    @Subscribe
    public void onEventMainThread(GetOneStockEvent event) {
        //只处理这里推送记录页面点击打开股票详情时,获取股票详情的响应
        if(event.getAction() != GetOneStock.ACTION_OPENSTOCK_INPUSHRECORD) return;
        if (event.getResponseCode() == NetWorkConstants.RESPONSE_CODE_OK) {
            StockInfoBean sib = JSON.parseObject(event.getmStockInfoBeanStr(), StockInfoBean.class);
            Intent intent = new Intent(getActivity(), StockDetailActivity.class);
            intent.putExtra("clickedStock", sib);
            startActivity(intent);
            getActivity().overridePendingTransition(R.anim.in_from_right, R.anim.out_from_left);
        }else{
            Log.d(TAG, event.getMessage());
            Toast.makeText(getActivity(), "网络连接失败,请重试!", Toast.LENGTH_LONG).show();
        }
    }

    @Subscribe
    public void onEventMainThread(DeletePushRecordEvent event) {
        ((MainActivity) getActivity()).stopProgress();
        ResponseBean rb = event.getmResponseBean();
        if (rb.getRespCode() == NetWorkConstants.RESPONSE_CODE_OK) {
            if(!DeletePushRecord.DELETE_ALL_FLAG.equals(event.getDeletedRecordId())) {
                for (PushRecord pr : GetPushRecord.pushRecords) {
                    if (String.valueOf(pr.getId()).equals(event.getDeletedRecordId())) {
                        GetPushRecord.pushRecords.remove(pr);
                        break;
                    }
                }
                Toast.makeText(getActivity(), "删除成功!", Toast.LENGTH_LONG).show();
            }else {
                GetPushRecord.pushRecords.clear();
                Toast.makeText(getActivity(), "清空成功!", Toast.LENGTH_LONG).show();
            }
            mRecordsAdapter.notifyDataSetChanged();
        }else {
            Log.d(TAG, rb.getErrorMsg());
            Toast.makeText(getActivity(), "删除失败,请重试!", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    class PushRecordsLvAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            if (GetPushRecord.pushRecords.size() == 0) {
                noItemTipLL.setVisibility(View.VISIBLE);
//                mHeaderLL.setVisibility(View.GONE);
                TextView tipTv = (TextView) noItemTipLL.findViewById(R.id.list_tip_txt);
                tipTv.setText("提醒记录为空!");
            }else{
                noItemTipLL.setVisibility(View.GONE);
//                mHeaderLL.setVisibility(View.VISIBLE);
            }
            return GetPushRecord.pushRecords.size();
        }

        @Override
        public Object getItem(int position) {
            return GetPushRecord.pushRecords.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHoler viewHoler = null;
            if (convertView == null) {
                LayoutInflater inflater = LayoutInflater.from(getActivity());
                convertView = inflater.inflate(R.layout.pushrecord_item, null);
                viewHoler = new ViewHoler();
                viewHoler.recordsDateTv = (TextView) convertView.findViewById(R.id.recordsDateTv);
                viewHoler.recrodsContentTv = (TextView) convertView.findViewById(R.id.recordsContentTv);
                convertView.setTag(viewHoler);
            } else {
                viewHoler = (ViewHoler) convertView.getTag();
            }
            final PushRecord pushRecord = GetPushRecord.pushRecords.get(position);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINESE);
            String wakeDate = sdf.format(pushRecord.getWakedDate());
            viewHoler.recordsDateTv.setText(wakeDate);

            String recordsContentTemp = "%s(%s)\n触发提醒价为: %s\n设置买入: %s;设置卖出: %s";
            String settedDown = pushRecord.getSettedDown() == null ? "无" : pushRecord.getSettedDown().toString();
            String settedUp = pushRecord.getSettedUp() == null ? "无" : pushRecord.getSettedUp().toString();
            String recordsContent = String.format(recordsContentTemp, pushRecord.getStockname(), pushRecord.getStocknum(), pushRecord.getWakedPrice(), settedDown, settedUp);
            viewHoler.recrodsContentTv.setText(recordsContent);
            ((RelativeLayout)viewHoler.recrodsContentTv.getParent()).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    GetOneStock gos = GetOneStock.build().setStockNum(pushRecord.getStocknum()).setAction(GetOneStock.ACTION_OPENSTOCK_INPUSHRECORD);
                    StockCenter.doReq(gos);
                }
            });
            ((RelativeLayout) viewHoler.recrodsContentTv.getParent()).setLongClickable(true);
            ((RelativeLayout) viewHoler.recrodsContentTv.getParent()).setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    Dialog dialog=new AlertDialog.Builder(getActivity())
                            .setTitle("删除这条记录")
                            .setMessage("确认删除吗？")
                            .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    DeletePushRecord deletePushRecord = DeletePushRecord.build();
                                    deletePushRecord.setDeleteFlag(String.valueOf(pushRecord.getId()));
                                    StockCenter.doReq(deletePushRecord);
                                    ((MainActivity) getActivity()).showProgress("正在删除...");
                                }
                            })
                            .setNegativeButton("取消",null).create();
                    dialog.show();
                    return false;
                }
            });
            return convertView;
        }

        class ViewHoler{
            public TextView recordsDateTv, recrodsContentTv;
        }

    }
}
